package chapter10_3_semaphore;

import javax.swing.plaf.multi.MultiMenuBarUI;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * @author Summerday
 */
public class SemaphoreTest3 {

    private static final int nThreads = 30;

    // 创建一个Semaphore 实例
    private static final Semaphore semaphore = new Semaphore(10);

    public static void main (String[] args) throws InterruptedException {
        // 创建线程池
        ExecutorService executorService = Executors.newFixedThreadPool(nThreads);

        for(int i= 1; i <= nThreads; i ++){
            executorService.execute(()->{
                try {
                    long start = System.currentTimeMillis();
                    semaphore.acquire();
                    TimeUnit.SECONDS.sleep(1);
                    semaphore.release();
                    long end = System.currentTimeMillis();
                    System.out.println(Thread.currentThread().getName() + " spend : " + (end - start));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }
        executorService.shutdown();
    }

}
